/*
 *	Copyright © 2015 Zhejiang SKT Science Technology Development Co., Ltd. All rights reserved.
 *	浙江斯凯特科技发展有限公司 版权所有
 *	http://www.28844.com
 */
package com.flycms.common.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

public class AgentUtils {


	// \b 是单词边界(连着的两个(字母字符 与 非字母字符) 之间的逻辑上的间隔),
	// 字符串在编译时会被转码一次,所以是 "\\b"
	// \B 是单词内部逻辑间隔(连着的两个字母字符之间的逻辑上的间隔)
	static String phoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i"
			+"|windows (phone|ce)|blackberry"
			+"|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp"
			+"|laystation portable)|nokia|fennec|htc[-_]"
			+"|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
	static String tableReg = "\\b(ipad|tablet|(Nexus 7)|up.browser"
			+"|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";


	//移动设备正则匹配：手机端、平板
	static Pattern phonePat = Pattern.compile(phoneReg, Pattern.CASE_INSENSITIVE);
	static Pattern tablePat = Pattern.compile(tableReg, Pattern.CASE_INSENSITIVE);

	/**
	 * 验证是否为手机访问
	 * @param request
	 * @return
	 */
	public static boolean judgeIsPhone(HttpServletRequest request){
		boolean _isPhone = false;
		if(StringUtils.isNoneBlank(request.getHeader("User-Agent"))){
			String _userAgent = request.getHeader("User-Agent").toLowerCase();
			Matcher _matcherPhone = phonePat.matcher(_userAgent);
			Matcher _matcherTable = tablePat.matcher(_userAgent);
			if(_matcherPhone.find() || _matcherTable.find()){
				_isPhone = true;
			}
		}
		return _isPhone;
	}
}
